import { reactive, ref } from "vue"

// 原图的信息
export const imgBox = reactive({
    width: 0,
    height: 0,

    // 偏移量
    moveLeft: 0,
    moveTop: 0,

    // 收缩
    scale: 1,

    // 旋转
    rotate: 0,

    //最初的宽度
    initWidth: 0,
    //最初的高度
    initHeight: 0
})

// 外框的信息
export const outerBox = reactive({
    width: 0,
    height: 0,
})

// 切块的信息
export const cutBox = reactive({
    width: 0,
    height: 0,
    // 偏移量
    moveLeft: 0,
    moveTop: 0,

    scale: 0
})


/**
 * 产生原图
 * @param v base64 或者blob
 */
export const changeImage = (v: string, callBack: Function) => {
    const imgDom = document.createElement("img")
    imgDom.src = v
    imgDom.onload = () => {

        // 宽高比例
        const widthHeightScale = imgDom.width / imgDom.height

        // 宽度处理
        const doWidth = () => {
            if (outerBox.width <= imgDom.width) {
                imgBox.width = outerBox.width
            } else {
                imgBox.width = imgDom.width
            }
            imgBox.height = imgBox.width / widthHeightScale
        }

        // 高度处理
        const doHeight = () => {
            if (outerBox.height <= imgDom.height) {
                imgBox.height = outerBox.height
            } else {
                imgBox.height = imgDom.height
            }
            imgBox.width = imgBox.height * widthHeightScale
        }

        // 宽框 或者 正方
        if (outerBox.width >= outerBox.height) {
            if (imgDom.width > imgDom.height) {
                doWidth()
            } else {
                doHeight()
            }
        }
        // 长框
        else {
            if (imgDom.width >= imgDom.height) {
                doWidth()
            } else {
                doHeight()
            }
        }


        imgBox.initWidth = imgBox.width

        imgBox.initHeight = imgBox.height

        //偏移量设置 让图居中显示
        imgBox.moveLeft = (outerBox.width - imgBox.width) / 2

        imgBox.moveTop = (outerBox.height - imgBox.height) / 2


        //生成图片
        generateImg(v, (base64: string) => {
            callBack(base64)
        })
    }
}

/**
 * 生成新图片
 * @param v base64 或者blob
 */
export const generateImg = (v: string, callBack: Function) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
    canvas.width = cutBox.width
    canvas.height = cutBox.height

    let img = new Image();

    img.src = v

    const showWidth = imgBox.width

    const showHeight = imgBox.height

    let imgStartX = imgBox.moveLeft - cutBox.moveLeft

    let imgStartY = imgBox.moveTop - cutBox.moveTop

    img.onload = () => {

        ctx.drawImage(img, imgStartX, imgStartY, showWidth, showHeight);

        const base64Data = canvas.toDataURL("image/png", 1)

        callBack(base64Data)
    }
}
